package com.mxpio.erp.equipment.controller;


import com.mxpio.erp.common.enums.NoticeStatusEnums;
import com.mxpio.erp.common.enums.OrderEnums;
import com.mxpio.erp.common.equipment.entity.RepairPickupNotice;
import com.mxpio.erp.common.equipment.entity.RepairPickupNoticeLine;
import com.mxpio.erp.common.equipment.service.RepairPickupNoticeService;
import com.mxpio.erp.common.jpa.model.Notice;
import com.mxpio.erp.common.order.policy.NoticeContext;
import com.mxpio.erp.common.order.service.NoticeService;
import com.mxpio.erp.common.technology.entity.Item;
import com.mxpio.erp.common.technology.service.ItemService;
import com.mxpio.erp.common.vo.OrderExcuteVo;
import com.mxpio.erp.equipment.policy.impl.EquipmentDefaultNoticePolicy;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.CrudType;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Tag(name = "RepairPickupNoticeController", description = "维修领料通知单接口")
@RestController
@RequestMapping("/erp/equipment/spotrepair/pickupnotice/")
public class RepairPickupNoticeController {

    @Autowired
    private RepairPickupNoticeService service;

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private ItemService itemService;

    @GetMapping("list")
    @Operation(summary = "维修领料通知单列表", description = "获取维修领料通知单列表（无分页）", method = "GET")
    public Result<List<RepairPickupNotice>> list(@Parameter(description="查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<RepairPickupNotice> noticeList = service.list(RepairPickupNotice.class, criteria);
        return Result.OK(noticeList);
    }
    @GetMapping("page")
    @Operation(summary = "维修领料通知单列表", description = "获取维修领料通知单列表（分页）", method = "GET")
    public Result<Page<RepairPickupNotice>> page(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<RepairPickupNotice> noticeList = service.listPage(RepairPickupNotice.class, page, criteria);
        return Result.OK(noticeList);
    }

    @GetMapping("list/{noticeNo}")
    @Operation(summary = "根据noticeNo获取维修领料通知单", description = "根据noticeNo获取维修领料通知单", method = "GET")
    public Result<RepairPickupNotice> getById(@Parameter(description="通知单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
        RepairPickupNotice noticeList = service.getById(RepairPickupNotice.class, noticeNo);
        return Result.OK(noticeList);
    }

    @DeleteMapping("remove/{noticeNos}")
    @Operation(summary = "根据noticeNo删除维修领料通知单", description = "删除维修领料通知单", method = "DELETE")
    public Result<RepairPickupNotice> remove(@Parameter(description="业务单号，多个单号用英文逗号分隔") @PathVariable(name = "noticeNos", required = true) String noticeNos) {
        String[] noticeNo = noticeNos.split(",");
        for(String key : noticeNo){
            service.delete(RepairPickupNotice.class, key);
        }
        return Result.OK();
    }

    @RequestMapping("save")
    @Operation(summary = "保存维修领料通知单", description = "保存维修领料通知单")
    public Result<RepairPickupNotice> save(@RequestBody RepairPickupNotice notice) {
        if (CrudType.SAVE.equals(notice.getCrudType())){
            notice.setNoticeDate(new Date());
            notice.setAccessType(OrderEnums.AccessType.OUT.getCode());
            notice.setPickingType(NoticeStatusEnums.NoticeType.SPP_OUT.getCode());
            notice.setNoticeStatus(NoticeStatusEnums.NoticeStatus.DRAFT.getStatusCode());//默认草稿
            List<RepairPickupNoticeLine> receivingOrderLines = notice.getNoticeLineList();
            for(RepairPickupNoticeLine line : receivingOrderLines) {
                Item item = itemService.getById(Item.class,line.getItemCode());
                line.setItemName(item.getItemName());
                line.setItemSpec(item.getItemSpec());
                line.setUnitCode(item.getUnitCode());
            }
        }else{
            List<RepairPickupNoticeLine> receivingOrderLines = notice.getNoticeLineList();
            for(RepairPickupNoticeLine line : receivingOrderLines) {
                if (CrudType.SAVE.equals(line.getCrudType())){
                    Item item = itemService.getById(Item.class,line.getItemCode());
                    line.setItemName(item.getItemName());
                    line.setItemSpec(item.getItemSpec());
                    line.setUnitCode(item.getUnitCode());
                }
            }
        }
        service.save(notice,new SmartCrudPolicyAdapter(){
            @Override
            public boolean beforeInsert(CrudContext context) {
                Object o = context.getEntity();
                if(o instanceof RepairPickupNoticeLine){
                    RepairPickupNotice receivingNotice = context.getParent();
                    ((RepairPickupNoticeLine) o).setNoticeNo(receivingNotice.getNoticeNo());
                }
                return true;
            }
        });
        return Result.OK(notice);
    }

    @PutMapping("commit/{noticeNo}")
    @Operation(summary = "提交通知单", description = "提交通知单", method = "PUT")
    @Transactional
    public Result<? extends Notice> commit(@Parameter(description="通知单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
        RepairPickupNotice notice = service.getById(RepairPickupNotice.class,noticeNo);
        if (!StringUtils.equals(notice.getNoticeStatus(),NoticeStatusEnums.NoticeStatus.DRAFT.getStatusCode())){
            return Result.error("仅草稿状态的通知单允许提交操作");
        }
        return noticeService.updateNoticeStatus(notice, NoticeStatusEnums.NoticeStatus.CREATE);//更新为开立状态，相当于待审核
    }

    @PutMapping("reject/{noticeNo}")
    @Operation(summary = "拒绝通知单", description = "拒绝通知单", method = "PUT")
    public Result<? extends Notice> close(@Parameter(description="通知单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
        RepairPickupNotice notice = service.getById(RepairPickupNotice.class,noticeNo);
    	return noticeService.updateNoticeStatus(notice, NoticeStatusEnums.NoticeStatus.REJECT);
    }

    @RequestMapping("execute/{noticeNo}")
    @Operation(summary = "通知单执行", description = "通知单执行")
    public Result<Object> excute(@PathVariable(name = "noticeNo", required = true) String noticeNo,
                                 @RequestBody OrderExcuteVo orderExcuteVo) {
        RepairPickupNotice notice = service.getById(RepairPickupNotice.class, noticeNo);
        if (notice.getNoticeStatus().equals(NoticeStatusEnums.NoticeStatus.CONFIRM.getStatusCode())){
            return Result.error("单据状态已发生变化，已确认状态单据不允许重复确认！");
        }
        NoticeContext context = noticeService.execute(notice, new EquipmentDefaultNoticePolicy(orderExcuteVo.getLines()));
        if(CollectionUtils.isEmpty(context.getErrors())) {
            return Result.OK();
        }else {
            return Result.error(context.getErrors().get(0));
        }
    }
}
